/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projeto.voztg.pkg2.pkg0.IHM;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.regex.*;
import javax.swing.JOptionPane;
import projeto.voztg.pkg2.pkg0.Config;
import projeto.voztg.pkg2.pkg0.Erro;
import projeto.voztg.pkg2.pkg0.FurbSpeech;
import projeto.voztg.pkg2.pkg0.SomWav;
import projeto.voztg.pkg2.pkg0.WordsReplace;

public class FrmPalavrasChave extends javax.swing.JFrame {

    File file = new File(Config.getCaminhoOutPut() + Config.getNome_Arq_Replace());
    private Properties wordsReplaceFileProperties;
    int contaEspaco = 0;

    public FrmPalavrasChave() {
        initComponents();

    }

    private void AtualizaLista() {
        Erro.setErro(false);
        list1.removeAll();
        if (file.exists() != true) {
            Erro.setErro("arquivo de reposição de palavras foi apagado");
            Config.CriarConfiguracoes();
            AtualizaLista();
        }
        String carregaPalavrasParaReposicao;

        FileReader reader;
        try {
            reader = new FileReader(Config.getCaminhoOutPut() + Config.getNome_Arq_Replace());
            BufferedReader br = new BufferedReader(reader);
            try {
                do {
                    carregaPalavrasParaReposicao = br.readLine();

                    if (carregaPalavrasParaReposicao != null) {
                        if (carregaPalavrasParaReposicao.charAt(0) != '#' && carregaPalavrasParaReposicao.charAt(0) != '<') {
                            list1.add(carregaPalavrasParaReposicao);
                        }
                    }

                } while (carregaPalavrasParaReposicao != null);

            } catch (IOException ex) {
                Erro.setErro(ex.getMessage());
            }
        } catch (FileNotFoundException ex) {
            Erro.setErro(ex.getMessage());

        }






    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        list1 = new java.awt.List();
        btnIncluir = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        label1 = new java.awt.Label();
        label2 = new java.awt.Label();
        btnTestar = new javax.swing.JButton();
        txtChave = new java.awt.TextField();
        txtPalavra = new java.awt.TextField();

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        list1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                list1MouseClicked(evt);
            }
        });

        btnIncluir.setText("incluir");
        btnIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncluirActionPerformed(evt);
            }
        });

        btnExcluir.setText("excluir");
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        label1.setText("CHAVE");

        label2.setText("PALAVRA");

        btnTestar.setText("testar");
        btnTestar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTestarActionPerformed(evt);
            }
        });

        txtChave.addTextListener(new java.awt.event.TextListener() {
            public void textValueChanged(java.awt.event.TextEvent evt) {
                txtChaveTextValueChanged(evt);
            }
        });

        txtPalavra.addTextListener(new java.awt.event.TextListener() {
            public void textValueChanged(java.awt.event.TextEvent evt) {
                txtPalavraTextValueChanged(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(list1, javax.swing.GroupLayout.PREFERRED_SIZE, 417, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnIncluir)
                                .addGap(29, 29, 29))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtChave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(20, 20, 20)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnTestar)
                                .addGap(275, 275, 275)
                                .addComponent(btnExcluir))
                            .addComponent(txtPalavra, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(138, 138, 138)
                        .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(250, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(list1, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtChave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtPalavra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnIncluir)
                    .addComponent(btnExcluir)
                    .addComponent(btnTestar))
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncluirActionPerformed
        Erro.setErro(false);
        if ("".equals(txtChave.getText()) || "".equals(txtPalavra.getText())) {
            JOptionPane.showMessageDialog(null, "chave ou valor não inserido");

        } else {


            if (file.exists() != true) {
                JOptionPane.showMessageDialog(null, "arquivo de reposição de palavras foi apagado");
                Erro.setErro("arquivo de reposição de palavras foi apagado");
            } else {
                wordsReplaceFileProperties = new Properties();

                try {
                    FileInputStream fiso = new FileInputStream(file);

                    wordsReplaceFileProperties.load(fiso);
                    String chave = txtChave.getText().trim().toLowerCase();
                    String padrao = "\\s{2,}";
                    Pattern regPat = Pattern.compile(padrao);//metodo para excluir excesso de espaços em uma string
                    String frase = txtPalavra.getText();
                    Matcher matcher = regPat.matcher(frase);
                    String valor = matcher.replaceAll(" ").trim().toLowerCase();//termina aqui

                    //System.out.println(valor);

                    if (wordsReplaceFileProperties.containsKey(chave) || wordsReplaceFileProperties.containsValue(valor)) {
                        JOptionPane.showMessageDialog(null, "chave ou valor já existentes");
                    } else {
                        int reply = JOptionPane.showConfirmDialog(null, "Deseja incluir a chave  " + chave.toUpperCase() + "?", "Inclusão", JOptionPane.YES_NO_OPTION);
                        if (reply == JOptionPane.YES_OPTION) {
                            wordsReplaceFileProperties.setProperty(chave, valor);
                            FileOutputStream fis = new FileOutputStream(file);
                            wordsReplaceFileProperties.store(fis, "inclusao da chave "+chave);//codificação de caracteres ISO 8859-1.                        
                            AtualizaLista();
                            WordsReplace.RecarregarReplace();
                            fis.close();
                            fiso.close();
                        } else {
                            fiso.close();
                        }

                    }
                } catch (IOException ex) {
                    Erro.setErro(ex.getMessage());
                }
                txtChave.setText("");
                txtPalavra.setText("");
                AtualizaLista();
            }
        }

    }//GEN-LAST:event_btnIncluirActionPerformed

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        Erro.setErro(false);
        if ("".equals(txtChave.getText())) {
            JOptionPane.showMessageDialog(null, "chave ou valor não selecionada");

        } else {

            if (file.exists() != true) {
                JOptionPane.showMessageDialog(null, "arquivo de reposição de palavras foi apagado");
                Erro.setErro("arquivo de reposição de palavras foi apagado");
            } else {
                wordsReplaceFileProperties = new Properties();

                try {
                    FileInputStream fiso = new FileInputStream(file);
                    wordsReplaceFileProperties.load(fiso);
                    String chave = txtChave.getText().toLowerCase();

                    if (wordsReplaceFileProperties.containsKey(chave)) {
                        int reply = JOptionPane.showConfirmDialog(null, "Deseja excluir a chave " + chave.toUpperCase() + "?", "Exclusão", JOptionPane.YES_NO_OPTION);
                        if (reply == JOptionPane.YES_OPTION) {
                            wordsReplaceFileProperties.remove(chave);
                            FileOutputStream fis = new FileOutputStream(file);
                            wordsReplaceFileProperties.store(fis, "remoção da chave "+chave);
                            WordsReplace.RecarregarReplace();



                            fis.close();
                            fiso.close();
                        } else {
                            fiso.close();
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "Não existe a chave indicada");
                    }


                } catch (IOException ex) {
                    System.out.println(ex.getMessage());
                }
                txtChave.setText("");
                txtPalavra.setText("");
                AtualizaLista();
            }

        }
    }//GEN-LAST:event_btnExcluirActionPerformed

    private void list1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_list1MouseClicked
        try {
            String ItemSelecionadoNaLista = list1.getSelectedItem();
            String divide[] = ItemSelecionadoNaLista.split("\\=");
            txtChave.setText(divide[0]);
            txtPalavra.setText(divide[1]);
        } catch (Exception x) {
            Erro.setErro(x.getMessage());
        }
    }//GEN-LAST:event_list1MouseClicked

    private void btnTestarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTestarActionPerformed
        
        new FurbSpeech().withVoice(Config.getVozSelecionada()).text(txtPalavra.getText()).to("discurso.wav").speech();
        SomWav s = new SomWav(Config.getCaminhoOutPut() + "discurso.wav");
        s.tocaSom();
    }//GEN-LAST:event_btnTestarActionPerformed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        AtualizaLista();
    }//GEN-LAST:event_formComponentShown

    private void txtChaveTextValueChanged(java.awt.event.TextEvent evt) {//GEN-FIRST:event_txtChaveTextValueChanged
         int i ;
        char[] Abrev = txtChave.getText().toCharArray();
        for (i = 0; i < Abrev.length; i++) {


            if (Character.isLetterOrDigit(Abrev[i]) == false && Abrev[i] != '?' && Abrev[i] != '.' && Abrev[i] != '!' && Abrev[i] != ',' && Abrev[i] != ' ') {

                JOptionPane.showMessageDialog(this, "Caracter  não permitido");
                String apagar = txtChave.getText().substring(0, txtChave.getText().length() - 1);
                txtChave.setText(apagar);
                txtChave.setSelectionStart(i);
            }
        }
    }//GEN-LAST:event_txtChaveTextValueChanged

    private void txtPalavraTextValueChanged(java.awt.event.TextEvent evt) {//GEN-FIRST:event_txtPalavraTextValueChanged
       int i ;
        char[] Abrev = txtPalavra.getText().toCharArray();
        for (i = 0; i < Abrev.length; i++) {


            if (Character.isLetterOrDigit(Abrev[i]) == false && Abrev[i] != '?' && Abrev[i] != '.' && Abrev[i] != '!' && Abrev[i] != ',' && Abrev[i] != ' ') {

                JOptionPane.showMessageDialog(this, "Caracter  não permitido");
                String apagar = txtPalavra.getText().substring(0, txtPalavra.getText().length() - 1);
                txtPalavra.setText(apagar);
                txtPalavra.setSelectionStart(i);
            }
        }

    }//GEN-LAST:event_txtPalavraTextValueChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnIncluir;
    private javax.swing.JButton btnTestar;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private java.awt.Label label1;
    private java.awt.Label label2;
    private java.awt.List list1;
    private java.awt.TextField txtChave;
    private java.awt.TextField txtPalavra;
    // End of variables declaration//GEN-END:variables
}
